<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 
        打乱数组： 如[1,2,3,4,5] => [1,3,2,5,4]
     -->
</head>

<body>

</body>

<script>
    let arr = [1, 2, 6];
    console.log('原数组为', arr);
    console.log('打乱后的数组为', breakArr(arr));


    //打乱数组，打乱的数组与原数组不同
    function breakArr(arr) {
        let indexArr = getNewArr(arr.length, 0, arr.length - 1);
        // console.log(indexArr, isOrder(indexArr));
        while (isOrder(indexArr)) {
            indexArr = getNewArr(arr.length, 0, arr.length - 1);
            // console.log(indexArr);//测试，重新生成下标数组
        }
        let arrPlus = [];
        for (let i = 0; i < arr.length; i++) {
            arrPlus.push(arr[indexArr[i]]);
        }
        return arrPlus;

    }

    function isOrder(arr) {
        let flag = true;
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] != i) {
                flag = false;
            }
        }
        return flag;
    }


    //生成数组函数，数组由n个min到max之间不重复的数生成
    function getNewArr(n, min, max) {
        let arr = [];
        for (let i = 0; i < n; i++) {
            let num;
            num = parseInt(Math.random() * (max - min + 1)) + min;
            // console.log(i, num, arr);//测试
            //如果随机数在数组中则重新生成随机数
            while (inArr(num, arr)) {
                num = parseInt(Math.random() * (max - min + 1)) + min;
            }
            arr[i] = num;
        }
        return arr;
    }
    //判断数在数组中
    function inArr(n, arr) {
        let flag = false;
        for (let i = 0; i < arr.length; i++) {
            if (n == arr[i]) {
                flag = true;
            }
        }
        return flag;
    }
</script>

</html>